package com.oig.sys.config;

import com.oig.sys.listener.JpaAuditListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;

@Slf4j
@RequiredArgsConstructor
@AutoConfigureAfter(JpaAuditConfiguration.class)
public class JpaAuditListenerRegisterConfig {


    private final EntityManagerFactory entityManagerFactory;
    private final JpaAuditListener jpaAuditListener;

    @PostConstruct
    public void registerListeners() {
        log.debug("register listener...");
        SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(jpaAuditListener);//对实体保存的监听
        registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(jpaAuditListener);//对实体修改的监听
        registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(jpaAuditListener);//对实体删除的监听
    }

}
